/**
 * 促销规则管理命名空间
 */
var salespromotionrule = {};

/**
 * 促销规则管理的操作对象
 */
salespromotionrule.operation = {};
salespromotionrule.operation.ADD_RULE = "add";
salespromotionrule.operation.EDIT_RULE = "edit";
salespromotionrule.operation.COPY_RULE = "copy";

salespromotionrule.shopEditFlag = 'n';
// 在增加或删除赠品、清空赠品列表、编辑赠品时，都会将此flag设置为true
salespromotionrule.giftEditFlag = 'n';
salespromotionrule.constrainGoodsEditFlag = 'n';

salespromotionrule.isRuleContentPageInit = false;

// 缓存页面的表格对象
var $ruleTable = null;

// 初始化iCheck组件
salespromotionrule.turn_on_iCheck = function(domElement) {
    return $('input[type="checkbox"],input[type="radio"]', domElement).iCheck({
        checkboxClass : 'icheckbox_flat-red',
        radioClass : 'iradio_flat-red'
    });
};

// 加载促销规则数据列表
salespromotionrule.initRulesTable = function(queryData) {
    if (!$ruleTable) {

        $ruleTable = $("#ruleTable").DataTable({
            "processing" : true,
            "serverSide" : true,
            "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100,500,1000 ] ],
            "dom" : '<"bottom"rtflp>',
            "searching" : false,
            "scrollX" : "100%",
            "scrollY" : "410px",
            "scrollCollapse": false,
            "destroy" : true,
            "pagingType" : "full_numbers",
            "deferRender" : true,
            "ajax" : {
                "url" : "/salesPromotion/ruleList.action",
                "type" : "get",
                "data" : function(d) {
                    d.formJson = encodeURI(JSON.stringify($("#advSearchPanel").data("queryData")));
                    d.quickSearch = encodeURI($("#quickSearch").val());
                }
            },
            "tableTools" : {
                "sRowSelect" : "bootstrap"
            },
            "columns" : [ {
                "data" : "checkbox",
                "class" : "text-center",
                "orderable" : false
            }, {
                "className" : "truncate-text tooltip-column-detail",
                "data" : "ruleName"
            }, {
                "data" : "ruleType",
                "orderable":false
            }, {
                "data" : "status",
                "orderable" : false,
                "visible" : false
            }, {
                "data" : "countingDateTypeStr",
                "orderable" : false
            }, {
                "data" : "countingDateStart",
            }, {
                "data" : "countingDateEnd",
            }, {
                "data" : "createTime",
            }, {
                "className" : "truncate-text tooltip-column-detail",
                "data" : "envolvingShops",
                "orderable" : false,
                "className" : "overflow"
            }, {
                "data" : "ruleDescription",
                "orderable" : false,
                "visible" : false
            }, {
                "data" : "operation",
                "orderable" : false
            } ],
            "columnDefs": [
                {"className": "truncate-text tooltip-column-detail", "targets":[1]},
                {"className": "truncate-text tooltip-column-detail", "targets":[2]},
                {"className": "truncate-text tooltip-column-detail", "targets":[3]},
                {"className": "truncate-text tooltip-column-detail", "targets":[4]},
                {"className": "truncate-text tooltip-column-detail", "targets":[5]},
                {"className": "truncate-text tooltip-column-detail", "targets":[6]},
                {"className": "truncate-text tooltip-column-detail", "targets":[7]},
                {"className": "truncate-text tooltip-column-detail", "targets":[8]},
                {"className": "truncate-text tooltip-column-detail", "targets":[9]}
            ]
        }).on('draw.dt', function() {
            $(".dataTables_scrollBody").css("overflow-y","overlay");
            $("#ruleTable").find("th.sorting_asc").removeClass("sorting_asc");
            $("#ruleTable").tooltip({
                selector : ".tooltip-column-detail",
                container : "body",
                title : function() {
                    //                    
                    if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                        return $(this).text();
                    }
                }
            });

            salespromotionrule.turn_on_iCheck($("#ruleTable"));
            $("#selecteAll").on("ifChanged", function() {
                if ($("#selecteAll").is(":checked")) {
                    $("#ruleTable").find(".icheck").iCheck("check");
                } else {
                    $("#ruleTable").find(".icheck").iCheck("uncheck");
                }
            });
            // 更新列表上三个状态的数值
            $.ajax({
                type : "get",
                url : "/salesPromotion/queryStateCount.action",
                contentType : "application/json;charset=utf-8",
                dataType : "json",
                data : {
                    formJson :encodeURI(JSON.stringify($("#advSearchPanel").data("queryData"))),
                    quickSearch : encodeURI($("#quickSearch").val())
                },
                async : false,
                success : function(data) {
                    if (data.result == "success") {
                        for (var i = 0, j = data.data.length; i < j; i++) {
                            $("#" + data.data[i].state + "Num").text(data.data[i].num);
                        }
                    } else {
                        window.top.window.showModalAlert(data.msg);
                    }
                },
                error : function(XMLHttpRequest, textStatus) {
                    if (XMLHttpRequest.status == 500) {
                        var result = eval("(" + XMLHttpRequest.responseText + ")");
                        alert(result.errorObject.errorText);
                    }
                }
            });
            
         // 文字过长截断显示悬浮框
            $("#ruleTable").tooltip({
                selector: ".tooltip-column-detail",
                container: "body",
                title: function() {
                    if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                        return $(this).text();
                    }
                }
            });
        });

    }
};

// 设置时间区间，用于区间的初始化和区间控件选择后的回调
salespromotionrule.setAdvDateRange = function(start, end) {
    if (!start || !end) {
        $('.reportrange span').html("请选择时间区间");
        $('#queryDateStart').val("");
        $('#queryDateEnd').val("");
    } else {
        $('.reportrange span').html(start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD'));
        $('#queryDateStart').val(start.format("YYYY-MM-DD"));
        $('#queryDateEnd').val(end.format("YYYY-MM-DD"));
    }
}

/*
 * 删除规则
 */
salespromotionrule.operation.deleteRule = function(ruleId) {

    if (ruleId) {
        window.top.window.showModalConfirm("确定要删除规则吗", function() {

            var data = {
                ruleId : ruleId
            }
            $.ajax({
                type : "GET",
                url : "/salesPromotion/deleteRule.action",
                contentType : "application/json;charset=utf-8",
                data : data,
                dataType : "json",
                async : false,
                success : function(data) {
                    if (data.result == "success") {
                        window.top.window.showScoMessage('ok', data.msg);
                        $ruleTable.draw();
                    } else {
                        window.top.window.showModalAlert(data.msg);
                    }
                },
                error : function(XMLHttpRequest, textStatus) {
                    if (XMLHttpRequest.status == 500) {
                        var result = eval("(" + XMLHttpRequest.responseText + ")");
                        alert(result.errorObject.errorText);
                    }
                }
            });
        });
    } else {
        window.top.window.showScoMessage('error', "未选择促销规则");
    }
};

/*
 * 获取可访问的平台店铺列表
 */
salespromotionrule.operation.getCurrentShopList = function() {
    var currentShopList = {};
    $.ajax({
        type : "GET",
        url : "/shop/shopListIncloudingClosed.action",
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        async : false,
        success : function(data) {
            if (data.result == "success") {
                currentShopList = data.data;
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
    return currentShopList;
};

// 绑定列表中的编辑按钮的点击事件
salespromotionrule.editRule = function(domElement) {
    // 获取规则ID
    var ruleId = $(domElement).attr("id") || "";
    var iframeSrc = "./views/salespromotion/activity/salespromotionruleedit.html?random=" + Math.random() + "&ruleId=" + ruleId;
    $("#ifmRuleEdit").attr("src", iframeSrc);
    $("#btnSave").unbind("click").bind("click", function() {
        // 调用子页面的保存方法
        window.top.frames["ifmRuleEdit"].window.ruleEdit.operation.saveRuleAdd(window.top.frames["ifmRuleEdit"].contentWindow);
        salespromotionrule.reloadRulesTable();
    });
    var ruleEditDialog = window.top.window.borrowCustomModalDialog($("#ruleIframeWindow"));
    ruleEditDialog.on('hide.bs.modal', function() {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
    });
    ruleEditDialog.on("hidden.bs.modal", function() {
        // 在弹出页隐藏后，重新加载促销规则数据列表
        salespromotionrule.reloadRulesTable();
    }).modal({
        show : true,
        backdrop : 'static'
    });
};

// 绑定列表中的复制按钮的点击事件
salespromotionrule.copyRule = function(domElement) {
    var ruleId = $(domElement).attr("id") || "";

    var iframeSrc = "./views/salespromotion/activity/salespromotionruleedit.html?random=" + Math.random() + "&copyRuleId=" + ruleId;
    $("#ifmRuleEdit").attr("src", iframeSrc);
    $("#btnSave").unbind("click").bind("click", function() {
        // 调用子页面的保存方法
        window.top.frames["ifmRuleEdit"].window.ruleEdit.operation.saveRuleAdd(window.top.frames["ifmRuleEdit"].contentWindow);
        salespromotionrule.reloadRulesTable();
    });
    var ruleEditDialog = window.top.window.borrowCustomModalDialog($("#ruleIframeWindow"));
    ruleEditDialog.on('hide.bs.modal', function() {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
    });
    ruleEditDialog.on("hidden.bs.modal", function() {
        // 在弹出页隐藏后，重新加载促销规则数据列表
        salespromotionrule.reloadRulesTable();
    }).modal({
        show : true,
        backdrop : 'static'
    });
};

// 绑定列表中的删除按钮的点击事件
salespromotionrule.deleteRule = function(domElement) {
    var ruleId = $(domElement).attr("id");
    salespromotionrule.operation.deleteRule(ruleId);

};
// 绑定批量删除按钮的点击事件
salespromotionrule.multiDeleteRule = function() {
    var ruleIds = $("#ruleTable").find("input.icheck:checked").map(function() {
        return $(this).attr("id");
    }).get().join();
    salespromotionrule.operation.deleteRule(ruleIds);
};

$(document).ready(function() {
    // 绑定按钮事件
    $("#btnAddRule").unbind().bind("click", salespromotionrule.addRuleInIframe);
    $("#btnDeleteRule").unbind().bind("click", salespromotionrule.multiDeleteRule);

    // 初始化促销规则列表——未启用的
    $("#advSearchPanel").data("isEnable", "a");

    $("#btnQuickSearch").bind("click", function() {
        salespromotionrule.reloadRulesTable();
    });

    // 过期
    $("#btnLoadExpireRule").on('show.bs.tab', function() {
        $("#advSearchPanel").data("isEnable", "y");
        $("#advSearchPanel").data("isExpire", "y");
        salespromotionrule.queryRuleData();
    });
    
    // 停用
    $("#btnLoadDisableRule").on('show.bs.tab', function() {
        $("#advSearchPanel").data("isEnable", "n");
        $("#advSearchPanel").data("isExpire", "");
        salespromotionrule.queryRuleData();
    });

    // 启用
    $("#btnLoadRunningRule").on('show.bs.tab', function() {
        $("#advSearchPanel").data("isEnable", "y");
        $("#advSearchPanel").data("isExpire", "n");
        salespromotionrule.queryRuleData();
    });

    // 未启用
    $("#btnLoadForbidRule").on('show.bs.tab', function(e) {
        $("#advSearchPanel").data("isEnable", "a");
        $("#advSearchPanel").data("isExpire", "");
        salespromotionrule.queryRuleData();
    });
    
    $("#advSearchReset").bind("click",function(){
        salespromotionrule.resetAdvSearch();
    });

    salespromotionrule.initAdvPage();

    salespromotionrule.initRulesTable();
});

// 根据查询条件重新加载表格
salespromotionrule.reloadRulesTable = function() {
    $ruleTable.ajax.reload();
};

// 公共方法
var getCheckResult = function(checkElement) {
    var returnValue = "n";
    if (checkElement instanceof jQuery) {
        if ($(checkElement).is(":checked")) {
            returnValue = "y";
        }
    } else if (checkElement === true) {
        returnValue = "y";
    }
    return returnValue;
};

salespromotionrule.addRuleInIframe = function() {
    var iframeSrc = "./views/salespromotion/activity/salespromotionruleedit.html?random=" + Math.random();
    $("#ifmRuleEdit").attr("src", iframeSrc);
    $("#btnSave").unbind("click").bind("click", function() {
        // 调用子页面的保存方法
        window.top.frames["ifmRuleEdit"].window.ruleEdit.operation.saveRuleAdd(window.top.frames["ifmRuleEdit"].contentWindow);
        salespromotionrule.reloadRulesTable();
    });
    var ruleEditDialog = window.top.window.borrowCustomModalDialog($("#ruleIframeWindow"));
    ruleEditDialog.on('hide.bs.modal', function() {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
    });
    ruleEditDialog.on("hidden.bs.modal", function() {
        // 在弹出页隐藏后，重新加载促销规则数据列表
        salespromotionrule.reloadRulesTable();
    }).modal({
        show : true,
        backdrop : 'static'
    });
};

salespromotionrule.viewRule  = function (domElement){
	var  btnType = "viewRule";
	var ruleId = $(domElement).attr("id") || "";

    var iframeSrc = "./views/salespromotion/activity/salespromotionruleedit.html?random=" + Math.random() + "&ruleId=" + ruleId+ "&btnType=" + btnType;
    $("#ifmRuleEdit").attr("src", iframeSrc);
    var ruleEditDialog = window.top.window.borrowCustomModalDialog($("#ruleIframeWindow"));
    ruleEditDialog.on('hide.bs.modal', function() {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
    });
    ruleEditDialog.on("hidden.bs.modal", function() {
        // 在弹出页隐藏后，重新加载促销规则数据列表
        salespromotionrule.reloadRulesTable();
    }).modal({
        show : true,
        backdrop : 'static'
    });
}

salespromotionrule.enableRule = function(domElement) {
    var ruleId = $(domElement).attr("id") || "";
    var param = {};
    param.ruleId = ruleId;

    window.top.window.showModalConfirm("确定要启用规则吗", function() {
        // 启用规则
        $.ajax({
            type : "GET",
            url : "/salesPromotion/enableRule.action",
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            data : param,
            async : false,
            success : function(data) {
                if (data.result == "success") {
                    window.top.window.showScoMessage('ok', "启用成功");
                    salespromotionrule.reloadRulesTable();
                } else {
                    window.top.window.showModalAlert(data.msg);
                }
            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });
    });
};

salespromotionrule.disableRule = function(domElement) {
    var ruleId = $(domElement).attr("id") || "";
    var param = {};
    param.ruleId = ruleId;
    window.top.window.showModalConfirm("确定要停用规则吗", function() {
        // 禁用规则
        $.ajax({
            type : "GET",
            url : "/salesPromotion/disableRule.action",
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            data : param,
            async : false,
            success : function(data) {
                if (data.result == "success") {
                    window.top.window.showScoMessage('ok', "停用成功");
                    salespromotionrule.reloadRulesTable();
                } else {
                    window.top.window.showModalAlert(data.msg);
                }
            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });
    });
};

var btnAdvSearchflg = false;

// 高级搜索页面初始化
salespromotionrule.initAdvPage = function() {
    var formObj = $("#frmAdvSearch");

    // 高级搜索
    $("#btnAdvSearch").click(function() {
        btnAdvSearchflg = true;
        if ($("#advSearchPanel").is(":hidden")) {
            $("#btnQuickSearch").hide();
            $("#advSearchPanel").show();
            $(this).children("i:eq(0)").removeClass("fa-angle-double-down");
            $(this).children("i:eq(0)").addClass("fa-angle-double-up");
        } else {
            salespromotionrule.resetAdvSearch();
            $("#advSearchPanel").hide();
            $("#btnQuickSearch").show();
            $(this).children("i:eq(0)").removeClass("fa-angle-double-up");
            $(this).children("i:eq(0)").addClass("fa-angle-double-down");
        }
    });

    // 初始化店铺列表
    var _shopListData = salespromotionrule.operation.getCurrentShopList();

    var _tempString = "";
    for (var i = 0, j = _shopListData.length; i < j; i++) {
        _tempString = '<option value="' + _shopListData[i].shopId + '">' + _shopListData[i].shopName + '</option>'
        $("#projectShopList").append($(_tempString));
    }

    // 日期区间选择控件初始化
    $('.reportrange', formObj).daterangepicker({
        ranges : {
            '过去7天' : [ moment().add('days', -7).startOf('day'), moment().add('days', -1).endOf('day') ],
            '过去3天' : [ moment().add('days', -3).startOf('day'), moment().add('days', -1).endOf('day') ],
            '本月' : [ moment().startOf('month').startOf('day'), moment().endOf('month').endOf('day') ],
            '未来30天' : [ moment().add('days', 1).startOf('day'), moment().add('days', 30).endOf('day') ],
            '下月' : [ moment().add('month', 1).startOf('month').startOf('day'), moment().add('month', 1).endOf('month').endOf('day') ]
        },
        timePicker : false,
        opens : 'right', // 日期选择框的弹出位置
        buttonClasses : [ 'btn btn-default' ],
        applyClass : 'btn-small btn-primary blue',
        cancelClass : 'btn-small',
        format : 'YYYY-MM-DD', // 控件中from和to 显示的日期格式
        separator : ' 到 ',
        locale : {
            applyLabel : '确定',
            cancelLabel : '取消',
            fromLabel : '起始时间',
            toLabel : '结束时间',
            customRangeLabel : '自定义',
            daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
            monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
            firstDay : 1
        }
    }, salespromotionrule.setAdvDateRange);

    salespromotionrule.setAdvDateRange();

    $("#advSearchPanel").click(function() {
        btnAdvSearchflg = true;
    })

    // 高级搜索“提交”按钮点击
    $("#advSearchSubmit").click(function(e) {
        salespromotionrule.queryRuleData();
    });
    salespromotionrule.resetAdvSearch();
    
    // 快速查询回车
    $('#quickSearch').keydown(function(e){
        if (e.keyCode == 13&&$('#btnQuickSearch').is(":visible")) {
            $('#btnQuickSearch').click();
        }
    });

};

salespromotionrule.queryRuleData = function() {
    var queryDateStart = $('#queryDateStart').val() ? $('#queryDateStart').val() + " 00:00:00" : "";
    var queryDateEnd = $('#queryDateEnd').val() ? $('#queryDateEnd').val() + " 23:59:59" : "";
    if (!!queryDateStart || !!queryDateEnd) {
        if ($('#queryDateType').val()=="") {
            window.top.window.showScoMessage('error', "请选择日期类型");
            return;
        }
    }
    var searchCondition = { // 高级检索
        querySendType : $("#querySendType").val(), // 订单编号
        queryShopId : $("#projectShopList").val(), // 店铺名称
        queryConstrainGoods : $("#queryConstrainGoods").val(), // 来源
        queryGift : $("#queryGift").val(), // 日期类型
        queryDateType : $("#queryDateType").val(), // 开始日期
        queryDateStart : queryDateStart, // 截止日期
        queryDateEnd : queryDateEnd, // 平台商品编号
        isExpire : $("#advSearchPanel").data("isExpire"),
        isEnable : $("#advSearchPanel").data("isEnable")
    };
    $("#advSearchPanel").data("queryData", searchCondition);
    salespromotionrule.reloadRulesTable();
};

salespromotionrule.resetAdvSearch = function() {
    var formObj = $("#frmAdvSearch");
    $("input", formObj).val("");
    
    salespromotionrule.setAdvDateRange();
    $("select.selectpicker", formObj).each(function(){
        $(this).selectpicker("val", "");
    });

    var searchCondition = { // 高级检索
        querySendType : "", // 订单编号
        queryShopId : "", // 店铺名称
        queryConstrainGoods : "", // 来源
        queryGift : "", // 日期类型
        queryDateType : "", // 开始日期
        queryDateStart : "", // 截止日期
        queryDateEnd : "", // 平台商品编号
        isExpire : $("#advSearchPanel").data("isExpire"),
        isEnable : $("#advSearchPanel").data("isEnable")
    };
    $("#advSearchPanel").data("queryData", searchCondition);
}